package com.usr.usrsimplebleassistent;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class Agreement {
    //    Int16 相当于short占2字节
//    Int32相当于int占4字节
//    Int64相当于long
//    long 占8字节
//    Byte相当于 byte 0~255
//    WORD 等于unsigned
//    short 0~65535

    public static byte[] blueCollectData1() throws Exception {
        //包头4字节
        byte[] bytes = new byte[28];
        for (int i = 0; i < 4; i++) {
            bytes[i] = 35;
        }
        int offset = 4;
        //长度
        int count = 26;
        byte[] lenByte = new byte[2];
        lenByte = BitConverterUtil.intToHexByteArray(count,2);
        System.out.println(byteArrayToHexStr(lenByte));
        System.arraycopy(lenByte, 0, bytes, offset, lenByte.length);
        offset += lenByte.length;
        //指令
        byte[] orderByte = new byte[4];
        orderByte = BitConverterUtil.intToHexByteArray(AgreeDefine.REQUEST_ID_BLUE_READ_FLOW_RANGE,4);
        System.arraycopy(orderByte, 0, bytes, offset, orderByte.length);
        offset += orderByte.length;
        //设备编号
        byte[] devCodeByte = new byte[4];
        devCodeByte = BitConverterUtil.intToHexByteArray(4822,4);
        System.arraycopy(devCodeByte, 0, bytes, offset, devCodeByte.length);
        offset += devCodeByte.length;
        //无整数
        byte[] emptyNumByte = new byte[1];
        emptyNumByte = BitConverterUtil.intToHexByteArray(0,1);
        System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
        offset += emptyNumByte.length;
        //无浮点
        System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
        offset += emptyNumByte.length;
        //无布尔
        System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
        offset += emptyNumByte.length;
        //无字符串
        System.arraycopy(emptyNumByte, 0, bytes, offset, emptyNumByte.length);
        offset += emptyNumByte.length;
        //时间戳
        byte[] time = new byte[8];
        time = getTimestamp();
        System.arraycopy(time, 0, bytes, offset, time.length);
        offset += 8;
        //校验码
        byte[] crc = new byte[2];
        crc = getCRC16(bytes, bytes.length);
        System.arraycopy(crc, 0, bytes, offset, crc.length);
        return bytes;
    }

    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        StringBuffer sb = null;
        while (strLen < strLength) {
            sb = new StringBuffer();
            sb.append("0").append(str);// 左补0
            // sb.append(str).append("0");//右补0
            str = sb.toString();
            strLen = str.length();
        }
        return str;
    }

    /**
     * 16进制的字符串表示转成字节数组
     * <p>
     * 16进制格式的字符串
     *
     * @return 转换后的字节数组
     **/

    public static void main(String[] args) {

        try {
            byte[] ret = blueCollectData1();
            String con = byteArrayToHexStr(ret);
            System.out.println(con);
            byte[] ceshi = hex2byte("1a");
            System.out.println(byteArrayToHexStr(ceshi));
        } catch (Exception e) {
            e.printStackTrace();
        }
        int count = 26;
        String hexString = Integer.toHexString(count);
        byte[] lenByte = new byte[2];
        lenByte = toByteArray(hexString);
        System.out.println(lenByte);
    }

    //16进制字符串转byte数组
    public static byte[] hex2byte(String hexString) throws Exception {
        byte[] hexStrBytes = hexString.getBytes();
        if (hexStrBytes.length % 2 != 0)
            throw new IllegalArgumentException("[" + hexString + "] lengh is even");
        byte[] bytes = new byte[hexStrBytes.length / 2];
        for (int i = 0; i < hexStrBytes.length; i += 2) {
            String item = new String(hexStrBytes, i, 2);
            int2onebyte(Integer.parseInt(item, 16), bytes, i / 2);
        }
        return bytes;
    }

    //int型转为byte
    public static void int2onebyte(int n, byte[] b, int off) throws Exception {
        if (!(n >= 0 && n <= 255)) throw new Exception(n + " exceed unsigned char range [0,255]!");
        b[off] = 0x00;
        b[off] |= n;
    }


    public static String toHexString(byte[] byteArray) {
        if (byteArray == null || byteArray.length < 1)
            throw new IllegalArgumentException("this byteArray must not be null or empty");

        final StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            if ((byteArray[i] & 0xff) < 0x10)//0~F前面不零
                hexString.append("0");
            hexString.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return hexString.toString().toLowerCase();
    }

    public static byte[] toByteArray(String hexString) {
//        if (StringUtils.isEmpty(hexString))
//            throw new IllegalArgumentException("this hexString must not be empty");
        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() / 2];
        int k = 0;
        for (int i = 0; i < byteArray.length; i++) {//因为是16进制，最多只会占用4位，转换成字节需要两个16进制的字符，高位在先
            byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);
            byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);
            byteArray[i] = (byte) (high << 4 | low);
            k += 2;
        }
        return byteArray;
    }

    /*输入16进制byte[]输出16进制字符串*/
    public static String byteArrayToHexStr(byte[] byteArray) {
        if (byteArray == null) {
            return null;
        }
        char[] hexArray = "0123456789ABCDEF".toCharArray();
        char[] hexChars = new char[byteArray.length * 2];
        for (int j = 0; j < byteArray.length; j++) {
            int v = byteArray[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }


    //64位双精度浮点数 时间戳8字节 47~54
    public static byte[] getTimestamp() {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date nowDate = new Date();
        Date lastDate = null;
        try {
            lastDate = myFormatter.parse("1905-01-01 00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long timeValue = (nowDate.getTime() - lastDate.getTime()) / 1000;
        return BitConverterUtil.longToHexByteArray(timeValue);
    }

    /**
     * CRC校验码
     *
     * @param data
     * @param length
     * @return
     */
    public static byte[] getCRC16(byte[] data, int length) {
        if (length > 0) {

//            UInt16 crc = 0xFFFF;
            int crc = IntUtil.getUint16(0xFFFF);
            for (int i = 0; i < length; i++) {
//                crc = (UInt16)(crc ^ (data[i]));
                crc = IntUtil.getUint16((crc ^ (data[i])));
                for (int j = 0; j < 8; j++) {
//                    crc = (crc & 1) != 0 ? (UInt16)((crc >> 1) ^ 0xA001) : (UInt16)(crc >> 1);
                    crc = (crc & 1) != 0 ? (IntUtil.getUint16(((crc >> 1) ^ 0xA001))) : (IntUtil.getUint16((crc >> 1)));
                }
            }
            byte hi = (byte) ((crc & 0xFF00) >> 8);
            byte lo = (byte) (crc & 0x00FF);
            return new byte[]{lo, hi};
        }
        return new byte[]{0, 0};
    }
//    public static Byte[] CRC16(Byte[] data, Int32 length)
//    {
//        if (length > 0)
//        {
//            UInt16 crc = 0xFFFF;
//            for (Int32 i = 0; i < length; i++)
//            {
//                crc = (UInt16)(crc ^ (data[i]));
//                for (Int32 j = 0; j < 8; j++)
//                {
//                    crc = (crc & 1) != 0 ? (UInt16)((crc >> 1) ^ 0xA001) : (UInt16)(crc >> 1);
//                }
//            }
//            Byte hi = (Byte)((crc & 0xFF00) >> 8);
//            Byte lo = (Byte)(crc & 0x00FF);
//
//            return new Byte[] { lo, hi};
//        }
//        return new Byte[] { 0, 0 };
//    }


}
